package com.zenithmind.news.websocket;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * WebSocket握手拦截器 - 重构后遵循单一职责原则
 * 专门负责WebSocket连接的握手验证和参数提取
 *
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WebSocketInterceptor implements HandshakeInterceptor {

    private final RedisTemplate<String, Object> redisTemplate;

    private static final String[] SUPPORTED_PARAMS = {"userId", "token", "categories", "tags"};

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                 WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        String uri = request.getURI().toString();
        log.debug("WebSocket握手请求：{}", uri);

        // 提取请求参数
        extractRequestParameters(request, attributes);

        // 获取客户端IP
        String clientIp = getClientIp(request);
        attributes.put("clientIp", clientIp);

        // 验证握手条件
        return validateHandshake(attributes, clientIp);
    }

    /**
     * 提取请求参数
     */
    private void extractRequestParameters(ServerHttpRequest request, Map<String, Object> attributes) {
        String query = request.getURI().getQuery();
        if (!StringUtils.hasText(query)) {
            return;
        }

        String[] params = query.split("&");
        for (String param : params) {
            String[] keyValue = param.split("=");
            if (keyValue.length == 2) {
                String key = keyValue[0];
                String value = keyValue[1];

                // 只处理支持的参数
                for (String supportedParam : SUPPORTED_PARAMS) {
                    if (supportedParam.equals(key)) {
                        attributes.put(key, value);
                        break;
                    }
                }
            }
        }
    }

    /**
     * 验证握手条件
     */
    private boolean validateHandshake(Map<String, Object> attributes, String clientIp) {
        String userId = (String) attributes.get("userId");
        if (!StringUtils.hasText(userId)) {
            log.warn("WebSocket握手失败：缺少用户ID，IP={}", clientIp);
            return false;
        }

        // Token验证逻辑
        String token = (String) attributes.get("token");
        if (!validateToken(token, userId)) {
            log.warn("WebSocket握手失败：token验证失败，用户ID={}, IP={}", userId, clientIp);
            return false;
        }

        log.info("WebSocket握手成功：用户ID={}, IP={}", userId, clientIp);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                             WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            log.error("WebSocket握手后异常", exception);
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(ServerHttpRequest request) {
        String xForwardedFor = request.getHeaders().getFirst("X-Forwarded-For");
        if (StringUtils.hasText(xForwardedFor)) {
            return xForwardedFor.split(",")[0].trim();
        }
        
        String xRealIp = request.getHeaders().getFirst("X-Real-IP");
        if (StringUtils.hasText(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddress() != null ?
               request.getRemoteAddress().getAddress().getHostAddress() : "unknown";
    }

    /**
     * 验证Token的有效性
     *
     * @param token 用户token
     * @param userId 用户ID
     * @return 是否有效
     */
    private boolean validateToken(String token, String userId) {
        if (!StringUtils.hasText(token) || !StringUtils.hasText(userId)) {
            return false;
        }

        try {
            // 从Redis中获取用户的token
            String cacheKey = "user:token:" + userId;
            Object cachedToken = redisTemplate.opsForValue().get(cacheKey);

            if (cachedToken == null) {
                log.warn("用户token不存在：{}", userId);
                return false;
            }

            // 验证token是否匹配
            boolean isValid = token.equals(cachedToken.toString());
            if (!isValid) {
                log.warn("用户token验证失败：{}", userId);
            }

            return isValid;

        } catch (Exception e) {
            log.error("Token验证异常：用户ID={}", userId, e);
            return false;
        }
    }
}
